"use client"

import { useState } from "react"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { SmilePlus, Heart, Reply } from "lucide-react"
import { EmojiPicker } from "@/components/comments/shared/emoji-picker"
import { toast } from "@/components/ui/use-toast"
import { cn } from "@/lib/utils"

interface Comment {
  id: number
  user: {
    name: string
    avatar: string
  }
  content: string
  timestamp: string
  likes: number
  isLiked?: boolean
  replies?: Comment[]
}

interface CommentSectionProps {
  playlistId: string
}

export default function CommentSection({ playlistId }: CommentSectionProps) {
  const [commentText, setCommentText] = useState("")
  const [replyText, setReplyText] = useState("")
  const [replyingTo, setReplyingTo] = useState<{ id: number; username: string } | null>(null)
  const [showEmojiPicker, setShowEmojiPicker] = useState(false)
  const [comments, setComments] = useState<Comment[]>([
    {
      id: 1,
      user: {
        name: "小琴",
        avatar: "/placeholder.svg",
      },
      content: "这张歌单每首歌都很棒！特别喜欢第一首，旋律太美了",
      timestamp: "2024年1月10日 19:38",
      likes: 42,
      replies: [
        {
          id: 2,
          user: {
            name: "音乐爱好者",
            avatar: "/placeholder.svg",
          },
          content: "同感！每一首都很用心",
          timestamp: "2024年1月10日 20:15",
          likes: 8,
        },
      ],
    },
  ])

  const handleComment = () => {
    if (!commentText.trim()) return

    const newComment: Comment = {
      id: Date.now(),
      user: {
        name: "当前用户",
        avatar: "/placeholder.svg",
      },
      content: commentText,
      timestamp: new Date().toLocaleString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      }),
      likes: 0,
      replies: [],
    }

    setComments([newComment, ...comments])
    setCommentText("")
    setShowEmojiPicker(false)
    toast({
      title: "评论成功",
      description: "你的评论已发布",
    })
  }

  const handleReply = () => {
    if (!replyText.trim() || !replyingTo) return

    const newReply: Comment = {
      id: Date.now(),
      user: {
        name: "当前用户",
        avatar: "/placeholder.svg",
      },
      content: replyText,
      timestamp: new Date().toLocaleString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit",
      }),
      likes: 0,
    }

    setComments(
      comments.map((comment) =>
        comment.id === replyingTo.id ? { ...comment, replies: [...(comment.replies || []), newReply] } : comment,
      ),
    )

    setReplyText("")
    setReplyingTo(null)
    setShowEmojiPicker(false)
    toast({
      title: "回复成功",
      description: "你的回复已发布",
    })
  }

  const handleLike = (commentId: number) => {
    setComments(
      comments.map((comment) =>
        comment.id === commentId
          ? {
              ...comment,
              likes: comment.isLiked ? comment.likes - 1 : comment.likes + 1,
              isLiked: !comment.isLiked,
            }
          : {
              ...comment,
              replies: comment.replies?.map((reply) =>
                reply.id === commentId
                  ? {
                      ...reply,
                      likes: reply.isLiked ? reply.likes - 1 : reply.likes + 1,
                      isLiked: !reply.isLiked,
                    }
                  : reply,
              ),
            },
      ),
    )
  }

  const addEmoji = (emoji: string) => {
    if (replyingTo) {
      setReplyText(replyText + emoji)
    } else {
      setCommentText(commentText + emoji)
    }
  }

  return (
    <div className="space-y-8">
      {/* Comment Input */}
      <div className="space-y-4">
        <div className="relative">
          <Textarea
            placeholder={replyingTo ? `回复 ${replyingTo.username}...` : "说说你的看法吧"}
            value={replyingTo ? replyText : commentText}
            onChange={(e) => (replyingTo ? setReplyText(e.target.value) : setCommentText(e.target.value))}
            className="min-h-[100px] pr-20"
            maxLength={300}
          />
          <div className="absolute bottom-2 right-2 text-sm text-muted-foreground">
            剩余{300 - (replyingTo ? replyText.length : commentText.length)}字
          </div>
        </div>
        <div className="flex justify-between items-center">
          <Button variant="ghost" size="icon" onClick={() => setShowEmojiPicker(!showEmojiPicker)}>
            <SmilePlus className="h-5 w-5" />
          </Button>
          <div className="flex items-center gap-2">
            {replyingTo && (
              <Button variant="outline" onClick={() => setReplyingTo(null)}>
                取消回复
              </Button>
            )}
            <Button onClick={replyingTo ? handleReply : handleComment}>{replyingTo ? "回复" : "发表评论"}</Button>
          </div>
        </div>
        {showEmojiPicker && <EmojiPicker onEmojiSelect={addEmoji} />}
      </div>

      {/* Comments List */}
      <div className="space-y-6">
        {comments.map((comment) => (
          <div key={comment.id} className="space-y-4">
            <div className="flex gap-4">
              <Avatar className="h-10 w-10">
                <AvatarImage src={comment.user.avatar} />
                <AvatarFallback>{comment.user.name[0]}</AvatarFallback>
              </Avatar>
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <span className="font-medium">{comment.user.name}</span>
                  <span className="text-sm text-muted-foreground">{comment.timestamp}</span>
                </div>
                <p className="text-sm whitespace-pre-line mb-2">{comment.content}</p>
                <div className="flex items-center gap-4">
                  <Button
                    variant="ghost"
                    size="sm"
                    className={cn(comment.isLiked && "text-red-500")}
                    onClick={() => handleLike(comment.id)}
                  >
                    <Heart className={cn("h-4 w-4 mr-1", comment.isLiked && "fill-current")} />
                    {comment.likes}
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setReplyingTo({ id: comment.id, username: comment.user.name })}
                  >
                    <Reply className="h-4 w-4 mr-1" />
                    回复
                  </Button>
                </div>
              </div>
            </div>

            {/* Replies */}
            {comment.replies && comment.replies.length > 0 && (
              <div className="ml-14 space-y-4">
                {comment.replies.map((reply) => (
                  <div key={reply.id} className="flex gap-4">
                    <Avatar className="h-8 w-8">
                      <AvatarImage src={reply.user.avatar} />
                      <AvatarFallback>{reply.user.name[0]}</AvatarFallback>
                    </Avatar>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="font-medium">{reply.user.name}</span>
                        <span className="text-sm text-muted-foreground">{reply.timestamp}</span>
                      </div>
                      <p className="text-sm whitespace-pre-line mb-2">{reply.content}</p>
                      <Button
                        variant="ghost"
                        size="sm"
                        className={cn(reply.isLiked && "text-red-500")}
                        onClick={() => handleLike(reply.id)}
                      >
                        <Heart className={cn("h-4 w-4 mr-1", reply.isLiked && "fill-current")} />
                        {reply.likes}
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  )
}

